package com.wujunshen.swagger.web.controller;

import com.wujunshen.swagger.exception.ResponseStatus;
import com.wujunshen.swagger.util.Constants;
import com.wujunshen.swagger.web.vo.response.BaseResponse;
import java.text.MessageFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;

/**
 * @author frank woo(吴峻申) <br>
 * email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2020/2/7 5:33 下午 <br>
 */
@Slf4j
public class BaseController {
    public BaseResponse<Object> getValidatedResult(BindingResult bindingResult) {
        if (!bindingResult.hasErrors()) {
            return null;
        }
        
        BaseResponse<Object> baseResponse = new BaseResponse<>();
        StringBuilder stringBuilder = new StringBuilder();
        
        bindingResult
                .getFieldErrors()
                .forEach(
                        error ->
                                stringBuilder
                                        .append(error.getField())
                                        .append(":")
                                        .append(error.getDefaultMessage())
                                        .append(" ,"));
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        
        String formattedMessage =
                MessageFormat.format(ResponseStatus.PARAMETER_VALIDATION.getMessage(), stringBuilder);
        baseResponse.setCode(ResponseStatus.PARAMETER_VALIDATION.getCode());
        baseResponse.setMessage(formattedMessage);
        baseResponse.setData(Constants.NULL_DATA);
        return baseResponse;
    }
}
